﻿using System;

namespace Uber.Data
{
    using System.Collections.Generic;
    using System.Data;
    using System.Data.SqlClient;
    using Core.Model;
    using Core.Repository;

    public class OProRepo : BaseRepo, IOProRepo
    {
        public OProRepo(IConnectionFactory connFactory) : base(connFactory)
        {
        }

        public OPro Get(string name)
        {
            using (var conn = new SqlConnection(Cs))
            {
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "getOProByName";
                    cmd.Parameters.Add("name", SqlDbType.NVarChar, 20).Value = name;
                    conn.Open();

                    using (var dr = cmd.ExecuteReader())
                    {
                        var o = new OPro();
                        while (dr.Read())
                        {
                            o.Pro = dr.GetString(0);
                            o.Price = dr.GetInt32(1);
                            o.Cid = dr.GetInt32(2);
                        }
                        return o;
                    }
                }
            }

        }

        public IEnumerable<OPro> GetPage(int page, int pageSize)
        {
            using (var conn = new SqlConnection(Cs))
            {
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "getOPros";
                    cmd.Parameters.Add("pageSize", SqlDbType.Int).Value = pageSize;
                    cmd.Parameters.Add("page", SqlDbType.Int).Value = page;
                    conn.Open();

                    using (var dr = cmd.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            var o = new OPro();
                            o.Pro = dr.GetString(0);
                            o.Price = dr.GetInt32(1);
                            o.Cid = dr.GetInt32(2);
                            yield return o;
                        }
                    }
                }
            }
        }

        public int Count()
        {
            using (var conn = new SqlConnection(Cs))
            {
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "getOProsCount";
                    conn.Open();

                    return (int)cmd.ExecuteScalar();
                }
            }
        }
    }
}